#include <stdlib.h>
#include "sector_node.h"
#include "fmt_prt.h"

static void sector_list_push(struct sector_list* list, struct sector_node* node)
{
    if(!list){
        //
        fmt_printf("%s failed, sector_list == NULL\n", __func__);
        return;
    }
    if(!node){
        //
        fmt_printf("%s failed, node == NULL\n", __func__);
        return;
    }

    if(list->head == NULL) {
        list->head = node;
    }else {
        node->next = list->head;
        list->head = node;
    }
    list->nodes++;
}

struct sector_node* sector_list_pop(struct sector_list* list)
{
    struct sector_node* ret;

    if(!list){
        //
        fmt_printf("%s failed, list == NULL\n", __func__);
        return NULL;
    }
    if(!list->nodes) {
        //
        fmt_printf("%s failed, node count == 0\n", __func__);
        return NULL;
    }
    ret = list->head;
    list->head = ret->next;
    list->nodes--;
    return ret;
}

struct sector_list* alloc_sector_list(uint32_t sector_size)
{
    struct sector_list* ret;

    ret = NULL;
    ret = (struct sector_list*)malloc(sizeof(struct sector_list));
    if(!ret) {
        //
        fmt_printf("%s failed, malloc failed\n", __func__);
        return NULL;
    }
    ret->head = NULL;
    ret->nodes = 0;
    ret->sector_size = sector_size;
    return ret;
}

struct sector_node* alloc_sector_node(struct sector_list* list, uint32_t sector)
{
    void* ret;
    struct sector_node* node;

    ret = NULL;
    node = NULL;
    if(!list){
        //
        fmt_printf("%s failed, list == NULL\n", __func__);
        return NULL;
    }

    node = (struct sector_node*)malloc(sizeof(struct sector_node));
    if(!node) {
        //
        fmt_printf("%s failed, node malloc failed\n", __func__);
        goto out;
    }

    ret = malloc(list->sector_size);
    if(!ret) {
        //
        fmt_printf("%s failed, node data malloc failed\n", __func__);
        goto sctr_mlc_fld;
    }

    node->data = ret;
    node->next = NULL;
    node->sector = sector;
    node->count = list->sector_size;
    sector_list_push(list, node);
    return node;

sctr_mlc_fld:
    free(node);
out:
    return NULL;
}

void free_sector_node(struct sector_node* node)
{
    if(!node){
        //
        fmt_printf("%s failed, node == NULL\n", __func__);
        return;
    }
    free(node->data);
    free(node);
}